package com.blog.user.service.impl;

import com.blog.user.dao.UserDao;
import com.blog.user.pojo.AuthUser;
import com.blog.user.service.UserService;
import com.blog.util.IdWorker;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public AuthUser findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public void add(AuthUser authUser) {
        String id = idWorker.nextId()+"";
        authUser.setId(id);
        // 对密码加密
        String password = authUser.getPassword();
        String hashpwd = BCrypt.hashpw(password, BCrypt.gensalt());
        authUser.setPassword(hashpwd);
        authUser.setStatus("y");// 默认启用
        authUser.setCreateDate(new Date());
        authUser.setUpdateDate(new Date());
        userDao.insert(authUser);
    }

    @Override
    public List<AuthUser> findAll(int page, int size, String query) {
        PageHelper.startPage(page,size);
        AuthUser authUser = new AuthUser();
        authUser.setUsername(query);
        return userDao.findAll(authUser);
    }

    @Override
    public void update(AuthUser authUser) {
        // 对密码加密
        String password = authUser.getPassword();
        String hashpwd = BCrypt.hashpw(password, BCrypt.gensalt());
        authUser.setPassword(hashpwd);

        String status = authUser.getStatus();
        if (StringUtils.isBlank(status)) {
            authUser.setStatus("y");
        }
        authUser.setUpdateDate(new Date());
        userDao.updateById(authUser);
    }

    @Override
    public void stopUser(String id) {
        AuthUser authUser = new AuthUser();
        authUser.setId(id);
        authUser.setStatus("n");
        userDao.updateById(authUser);
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public AuthUser findById(String id) {
        return userDao.selectById(id);
    }

    @Override
    public void cancelUser(String id) {
        AuthUser authUser = new AuthUser();
        authUser.setId(id);
        String random = RandomStringUtils.randomNumeric(6);
        authUser.setUsername("账号已注销" + random);
        authUser.setMobile(null);
        authUser.setFullname(null);
        authUser.setStatus("n");
        userDao.updateById(authUser);
    }
}
